/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.PrimaryGenerater;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.entity.vo.InvoicePayRecord;
import com.jeeplus.modules.fee.service.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 应收结算单Controller
 * @author weisong
 * @version 2017-09-22
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/receivables")
public class ReceivablesController extends BaseController {

	@Autowired
	private ReceivablesService receivablesService;
	@Autowired
	private PayableService payableService;
	@Autowired
	private ConsignorService consignorService;
	@Autowired
	private ReceivablesDetailService receivablesDetailService;
	@Autowired
	private OpenInvoiceService openInvoiceService;
	@Autowired
	private OpenInvoiceDetailService openInvoiceDetailService;
	@Autowired
	private BillDetailService billDetailService;
	@Autowired
	private DetailService detailService;

	@ModelAttribute
	public Receivables get(@RequestParam(required=false) String id) {
		Receivables entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = receivablesService.get(id);
		}
		if (entity == null){
			entity = new Receivables();
		}
		return entity;
	}
	
	/**
	 * 应收结算单列表页面
	 */
	@RequiresPermissions("fee:receivables:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/receivablesList";
	}
	
		/**
	 * 应收结算单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivables:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Receivables receivables, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Receivables> page = receivablesService.findPage(new Page<Receivables>(request, response), receivables); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应收结算单表单页面
	 */
	@RequiresPermissions(value={"fee:receivables:view","fee:receivables:add","fee:receivables:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Receivables receivables, Model model) {
		model.addAttribute("receivables", receivables);
		if(StringUtils.isBlank(receivables.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String payableId = request.getParameter("payableId");
		String typeSign = request.getParameter("typeSign");
		//点击应付结算单的多收冲账按钮后将原结算单信息带入新增的结算单
		if (StringUtils.isNotEmpty(payableId)) {
			model.addAttribute("payableId", payableId);
			model.addAttribute("typeSign", typeSign);
			Payable payable = payableService.get(payableId);
			if (null != payable) {
				//设置结算方
				receivables.setPayerName(payable.getPayee());
				//设置结算单号
				receivables.setClearingNo(payable.getClearingNo());
			}
		}
		String receId = request.getParameter("receId");
		//点击应收结算单的少收补票按钮后将原结算单信息带入新增的结算单
		if (StringUtils.isNotEmpty(receId)) {
			model.addAttribute("receId", receId);
			Receivables rece = receivablesService.get(receId);
			if (null != rece) {
				//设置结算方
				receivables.setPayerName(rece.getPayerName());
				//设置结算单号
				receivables.setClearingNo(rece.getClearingNo());
			}
		}
		model.addAttribute("feeReceivables", receivables);
		//供结算方下拉框使用
		Consignor cc = new Consignor();
		List<Consignor> consignors = consignorService.findList(cc);
		model.addAttribute("consignors", consignors);
		//查询应收结算单与应收结算单子表相关的数据
		ReceivablesDetail feeReceivablesDetail = new ReceivablesDetail();
		Receivables receivables1 = receivablesService.get(receivables.getId());
		if (receivables1 != null) {
			feeReceivablesDetail.setFeeReceivables(receivables1);
			List<ReceivablesDetail> list = receivablesDetailService.findList(feeReceivablesDetail);
			if (null != list && list.size() > 0) {
				model.addAttribute("list", list);
				model.addAttribute("flag", "receivables");
			}
		}
		//来自发票form页面查看的标记
		String different = request.getParameter("different");
		if (null != different && different != "") {
			model.addAttribute("different", different);
		}
		//当应收账款不为空时调用收票付款记录的方法
		if (null != receivables) {
			InvoicePayRecord(receivables.getId(), model);
		}
		return "modules/fee/receivablesForm";
	}

	/**
	 * 保存应收结算单
	 */
	@RequiresPermissions(value={"fee:receivables:add","fee:receivables:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Receivables receivables, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception{
		if (!beanValidator(model, receivables)){
			return form(receivables, model);
		}

		//获取原应收结算单id
		String receId = request.getParameter("receId") == null ? "" : request.getParameter("receId");
		//获取原应付结算单id
		String payableId = request.getParameter("payableId") == null ? "" : request.getParameter("payableId");
		//获取结算金额
		String cm = request.getParameter("payMoney");
		Double settlement = StringUtils.isEmpty(cm) ? 0.00 : Double.parseDouble(cm);
		//获取备注
		String comment = request.getParameter("remarks");
		if (StringUtils.isNotEmpty(receId)) {
			if (null != settlement && StringUtils.isNotEmpty(comment)) {
				//调用保存纠错之后的应收结算单【少收补票】
				saveCorrectionFeeReceivables(receId, receivables, settlement, comment);
				addMessage(redirectAttributes, "保存应收账款成功");
			}
		} else if (StringUtils.isNotEmpty(payableId)) {
			if (null != settlement && StringUtils.isNotEmpty(comment)) {
				//调用保存纠错之后的应付结算单【多收冲账】
				saveCorrectionPayable(payableId, receivables, settlement, comment);
				addMessage(redirectAttributes, "保存应收账款成功");
				return "redirect:" + Global.getAdminPath() + "/fee/payable/?repage";
			}
		}else {
			//新增或编辑表单保存
			//生成单号
			String number = "";
			Receivables receivables1 = receivablesService.findClearingNoAndBusyDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");    //初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == receivables1) {
				number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", null);
			} else {
				if (String.valueOf(format1.format(receivables1.getBusyDate())).equals(String.valueOf(format1.format(new Date())))) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", receivables1.getClearingNo());
				} else {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", null);
				}
			}
			//获取结算金额
			String clearMoney = request.getParameter("payMoney");
			Double clear = StringUtils.isNotEmpty(clearMoney) ? Double.parseDouble(clearMoney) : 0.00;
			receivables.setClearingNo(number);
			if (clear != null) {
				receivables.setPayMoney(clear);
			}
			receivablesService.save(receivables);//保存
			// 保存应收结算单明细
			// 获取费用明细表的id并保存
			String temp_ids = request.getParameter("ids") != null ? request.getParameter("ids") : "";
			if (StringUtils.isNotEmpty(temp_ids)) {
				saveReceivables(temp_ids, receivables);
			}
		}
		addMessage(redirectAttributes, "保存应收结算单成功");
		return "redirect:"+Global.getAdminPath()+"/fee/receivables/?repage";
	}
	
	/**
	 * 删除应收结算单
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivables:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Receivables receivables, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		receivablesService.delete(receivables);
		j.setMsg("删除应收结算单成功");
		return j;
	}
	
	/**
	 * 批量删除应收结算单
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivables:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//根据应收结算单id查询应收结算单明细表
			ReceivablesDetail feeReceivablesDetail = new ReceivablesDetail();
			feeReceivablesDetail.setFeeReceivables(receivablesService.get(id));
			List<ReceivablesDetail> list = receivablesDetailService.findList(feeReceivablesDetail);
			for (int i = 0; i < list.size(); i++) {
				//System.out.println(list.get(i).getFeeDetail().getId());
				//获取应收结算单明细表中的费用明细表的id。修改费用明细表的状态
				detailService.updateStatusById(Detail.updateStatus1, list.get(i).getFeeDetail().getId());
				//删除应收结算单明细表
				receivablesDetailService.delete(list.get(i));
			}
			receivablesService.delete(receivablesService.get(id));
		}

		j.setMsg("删除应收结算单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivables:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Receivables receivables, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收结算单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Receivables> page = receivablesService.findPage(new Page<Receivables>(request, response, -1), receivables);
    		new ExportExcel("应收结算单", Receivables.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收结算单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:receivables:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Receivables> list = ei.getDataList(Receivables.class);
			for (Receivables receivables : list){
				try{
					receivablesService.save(receivables);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收结算单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收结算单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收结算单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/receivables/?repage";
    }
	
	/**
	 * 下载导入应收结算单数据模板
	 */
	@RequiresPermissions("fee:receivables:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收结算单数据导入模板.xlsx";
    		List<Receivables> list = Lists.newArrayList(); 
    		new ExportExcel("应收结算单数据", Receivables.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/receivables/?repage";
    }

	/**
	 * 查询收票付款记录
	 *
	 * @param id 应付结算单id
	 */
	public void InvoicePayRecord(String id, Model model) {
		if (StringUtils.isNotEmpty(id)) {
			List<InvoicePayRecord> iprList = new ArrayList<InvoicePayRecord>();
			InvoicePayRecord ipr = null;
			//获取发票记录
			List<OpenInvoice> openInvoices = openInvoiceService.findOpenInvoiceByInvoiceDetail(id);
			//合计（一张结算单的总开票金额和总核销金额）
			double totalInvoice = 0;
			double totalVcamoney = 0;
			for (OpenInvoice fpi : openInvoices) {
				//new一个VO类[用来封装开票收款记录]
				ipr = new InvoicePayRecord();
				ipr.setInvoiceId(fpi.getId());    //发票id
				ipr.setInvoiceNo(fpi.getInvoiceNo());    //发票号
				ipr.setInvoiceDate(fpi.getInvoiceDate());    //开票时间
				ipr.setInvoiceTotalMoney(fpi.getInvoiceMoney());    //发票总金额
				ipr.setVcaTotalMoney(fpi.getVcaMoney());    //核销总金额
				//根据结算单id和发票主表id获取发票子表
				System.out.println(fpi.getId());
				OpenInvoiceDetail invoiceDetail = openInvoiceDetailService.findAllByReceivableId(id, fpi.getId());
				//设置本次开票金额
				ipr.setInvMoney(invoiceDetail.getInvMoney());
				//计算合计的开票金额
				totalInvoice += invoiceDetail.getInvMoney();
				//获取付款单子表
				List<BillDetail> billDetails = billDetailService.findBillDetailByInvoiceId(fpi.getId(), invoiceDetail.getId());
				double theVcaMoney = 0;
				for (BillDetail fbd : billDetails) {
					theVcaMoney += fbd.getTheVcaMoney();
				}
				//设置本次核销金额
				ipr.setTheVcaMoney(theVcaMoney);
				//计算合计的核销金额
				totalVcamoney += theVcaMoney;
				//设置付款单子表
				ipr.setBillDetails(billDetails);
				//将对象添加到iprList
				iprList.add(ipr);
			}
			model.addAttribute("iprList", iprList);
			model.addAttribute("totalInvoice", totalInvoice);
			model.addAttribute("totalVcamoney", totalVcamoney);
		}
	}


	/**
	 * 保存应收结算单明细
	 */
	public void saveReceivables(String temp_ids,Receivables receivables){
		// 保存应收结算单明细
		// 获取费用明细表的id并保存
		ReceivablesDetail frd = null;

		String[] _ids = temp_ids.split(","); //
		// 将form页面取的id值循环遍历
		if (_ids.length != 0) {
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					frd = new ReceivablesDetail();
					Detail feeDetail = detailService.get(id);
					frd.setFeeDetail(feeDetail);// 费用明细
					frd.setBusyDate(feeDetail.getBusyDate());// 业务日期
					frd.setFeeAgreeName(feeDetail.getFeeAgreement());// 计费协议
					frd.setFeeType(feeDetail.getFeeType());// 费用类型
					frd.setPayMoney(feeDetail.getPayMoney());// 计费金额
					frd.setClearingMoney(feeDetail.getClearingMoney());// 结算金额

					frd.setFeeReceivables(receivables);// 应收账款
					receivablesDetailService.save(frd);
					// 修改计费费用明细表的状态
					detailService.updateStatusById(Detail.updateStatus, id);
				}
			}
		}
	}

	/**
	 * 在应付结算单中点击多收冲账按钮【应收结算单】
	 *
	 * @param payableId      原结算单id
	 * @param feeReceivables
	 * @param payMoney       结算金额
	 * @param comment        备注
	 */
	public void saveCorrectionPayable(String payableId, Receivables feeReceivables, Double payMoney, String comment) {
		Payable payable = payableService.get(payableId);
		if (null != payable) {
			//设置结算方
			feeReceivables.setPayerName(payable.getPayee());
			//设置结算单号
			feeReceivables.setClearingNo(payable.getClearingNo());
			//设置结算金额
			feeReceivables.setPayMoney(payMoney);
			//设置备注
			feeReceivables.setRemarks(comment);
			receivablesService.save(feeReceivables);
		}
	}

	/**
	 * 保存点击少收补票按钮之后的应收结算单
	 *
	 * @param receId         原结算单id
	 * @param feeReceivables
	 * @param payMoney       结算金额
	 * @param comment        备注
	 */
	public void saveCorrectionFeeReceivables(String receId, Receivables feeReceivables, Double payMoney, String comment) {
		Receivables receivables = receivablesService.get(receId);
		if (null != receivables) {
			//设置结算方
			feeReceivables.setPayerName(receivables.getPayerName());
			//设置结算单号
			feeReceivables.setClearingNo(receivables.getClearingNo());
			//设置结算金额
			feeReceivables.setPayMoney(payMoney);
			//设置备注
			feeReceivables.setRemarks(comment);
			receivablesService.save(feeReceivables);
		}
	}

	/**
	 * 修改状态
	 *
	 * @param id   应收结算单id
	 * @param type 判断页面请求路径 form:跳转到form页面 list:跳转到list页面
	 * @return
	 */
	@RequestMapping(value = "updateStatus")
	public String updateStatus(String id, @RequestParam(value = "type") String type) {
		if (StringUtils.isEmpty(id)) {
			return "redirect:" + Global.getAdminPath() + "/fee/receivables/?repage";
		}
		//获得应付结算单主表
		Receivables feeReceivables = receivablesService.get(id);
		//更新状态
		if (feeReceivables.getStatus() < Receivables.updateStatus3) {
			receivablesService.updateStatusAndMoneyById(Receivables.updateStatus1, null, null, null, null, id);
		}
		if (type.equals("form")) {
			return "redirect:" + Global.getAdminPath() + "/fee/receivables/form?id=" + id;
		} else {
			return "redirect:" + Global.getAdminPath() + "/fee/receivables/?repage";
		}
	}

	/**
	 * 当点击list页面的已确认按钮时修改状态【可批量可单个】
	 */
	@RequestMapping(value = "updateStatusTwo")
	public @ResponseBody AjaxJson updateStatusTwo(String ids,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		//String ids = request.getParameter("ids");
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//获得应付结算单主表
			Receivables feeReceivables = receivablesService.get(id);
			//更新状态
			if (feeReceivables.getStatus() < Receivables.updateStatus3) {
				receivablesService.updateStatusAndMoneyById(Receivables.updateStatus1, null, null, null, null, id);
			}
		}
		j.setMsg("应收结算单状态修改成功");
		return j;
	}

	/**
	 * 获取弹出窗口的数据
	 */
	@RequestMapping(value="findAllDetail")
	public @ResponseBody String findAllDetail(Detail feeDetail, HttpServletRequest request, HttpServletResponse response){
		// 判断引入明细的状态是否为未结算
		String _status = request.getParameter("status");
		//获取查询框输入的值
		String startDate = request.getParameter("startTime");
		String endDate = request.getParameter("endTime");
		//获取结算方
		String clearId = request.getParameter("balance");
		//判断状态不为空
		if (StringUtils.isNotEmpty(_status)) {
			Integer status = Integer.parseInt(_status);
			feeDetail.setStatus(status);
		}
		//判断结算方不为空
		if (StringUtils.isNotEmpty(clearId)) {
			Consignor f = new Consignor();
			f.setId(clearId);
			feeDetail.setClearUnit(f);
		}
		//判断查询时间是否为空
		if(null != startDate && startDate != "" && null != endDate && endDate != ""){
			//String转化为Date
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start = null;//开始时间
			Date end = null;//结束时间
			try {
				start = sdf.parse(startDate+" 00:00:00");//开始时间
				end = sdf.parse(endDate+" 23:59:59");//结束时间
			} catch (ParseException e) {
				e.printStackTrace();
			}
			feeDetail.setStartDate(start);
			feeDetail.setEndDate(end);
		}
		//feeType:0是收入  1是支出
		String _feeType = request.getParameter("feeType");
		if(StringUtils.isNotEmpty(_feeType)){
			Type feeType = new Type();
			feeType.setFeeType(Integer.parseInt(_feeType));
			feeDetail.setFeeType(feeType);
		}
		List<Detail> list  = detailService.findList(feeDetail);
		String result = JsonMapper.toJsonString(list);
		return result;
	}

	/**
	 * 点击关闭结算单按钮时更新结算单状态和关闭原因
	 */
	@RequestMapping(value = "closeFeeReceivables")
	public @ResponseBody
	int closeFeeReceivables(HttpServletRequest request) {
		//获取结算单id
		String receId = request.getParameter("id");
		//获取关闭原因
		String closeReasn = request.getParameter("closeReason");
		int i = 1;
		//根据id获取结算单
		if (StringUtils.isNotEmpty(receId)) {
			Receivables feeReceivables = receivablesService.get(receId);
			//修改状态为已关闭
			feeReceivables.setStatus(Receivables.CLOSED);
			if (StringUtils.isNotEmpty(closeReasn)) {
				feeReceivables.setCloseReason(closeReasn);
			}
			receivablesService.save(feeReceivables);
		}
		return i;
	}

	/**
	 * 开票操作（跳转到新增发票页面）
	 */
	@RequestMapping(value = "invoiceOperation")
	public String invoiceOperation(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		//如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/receivables/?repage";
		if (StringUtils.isNotEmpty(ids)) {    //判断ids是否为空
			String[] _ids = ids.split(",");
			List<Receivables> list = new ArrayList<Receivables>();
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Receivables feeReceivables = receivablesService.get(id);
					list.add(feeReceivables);
				}
			}
			redirectAttributes.addFlashAttribute("list", list);
			redirectAttributes.addFlashAttribute("flag", "receivable");
			redirectAttributes.addFlashAttribute("ids", ids);
			redirectAttributes.addFlashAttribute("type", request.getParameter("type"));
			String target = request.getParameter("target") == null ? "ableList" : "invoiceList";
			url = "/fee/openInvoice/form?target=" + target;
		}
		return "redirect:" + Global.getAdminPath() + url;
	}

	/**
	 * 跳转到新增应收账款页面
	 */
	@RequestMapping(value = "addPayable")
	public @ResponseBody String addPayable(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes) {
		// 如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/detail/?repage";
		List<Detail> list = new ArrayList<Detail>();
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Detail feeDetail = detailService.get(id);
					list.add(feeDetail);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 计费明细页面结算生成结算单
	 */
	@RequiresPermissions(value = {"fee:receivables:add", "fee:receivables:edit"}, logical = Logical.OR)
	@RequestMapping(value = "balanceSave")
	public @ResponseBody
	String balanceSave(@RequestParam(value = "ids") String ids, @RequestParam(value = "clearUnit") String clearUnit,
					   @RequestParam(value = "clearMon") String money, @RequestParam(value = "remark") String remark) {
		if (StringUtils.isNotEmpty(ids) && StringUtils.isNotEmpty(clearUnit) && StringUtils.isNotEmpty(money)) {
			Receivables feeReceivables = new Receivables();
			feeReceivables.setStatus(0);
			//生成单号
			String number = "";
			Receivables receivables = receivablesService.findClearingNoAndBusyDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");    //初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == receivables) {
				number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", null);
			} else {
				if (String.valueOf(format1.format(receivables.getBusyDate())).equals(String.valueOf(format1.format(new Date())))) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", receivables.getClearingNo());
				} else {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YSJS", null);
				}
			}
			feeReceivables.setClearingNo(number);
			feeReceivables.setBusyDate(new Date());
			Consignor payee = consignorService.findByName(clearUnit);
			feeReceivables.setPayerName(payee);
			feeReceivables.setPayMoney(Double.parseDouble(money));
			feeReceivables.setRemarks(StringUtils.isEmpty(remark) ? "" : remark);
			receivablesService.save(feeReceivables);
			//开始保存子表
			ReceivablesDetail frd = null;
			String[] _ids = ids.split(","); //
			// 将form页面取的id值循环遍历
			if (_ids.length != 0) {
				for (String id : _ids) {
					if (StringUtils.isNotEmpty(id)) {
						frd = new ReceivablesDetail();
						Detail feeDetail = detailService.get(id);
						frd.setFeeDetail(feeDetail);// 费用明细
						frd.setBusyDate(feeDetail.getBusyDate());// 业务日期
						frd.setFeeAgreeName(feeDetail.getFeeAgreement());// 计费协议
						frd.setFeeType(feeDetail.getFeeType());// 费用类型
						frd.setPayMoney(feeDetail.getPayMoney());// 计费金额
						frd.setClearingMoney(feeDetail.getClearingMoney());// 结算金额

						frd.setFeeReceivables(feeReceivables);// 应收账款
						receivablesDetailService.save(frd);
						// 修改计费费用明细表的状态
						detailService.updateStatusById(Detail.updateStatus, id);
					}
				}
			}
			return "0";
		} else {
			return "1";
		}
	}




}